package com.jprocms.module.cms.util;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.common.util.http.HttpUtils;
import com.jpro.module.infra.api.config.FileConfigApi;
import com.jpro.module.infra.api.config.dto.FileConfigRespVO;
import com.jpro.module.infra.api.file.FileApi;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.framework.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Html 工具类
 */
@Slf4j
public class HtmlParserUtil {

    /**
     * 提取html中图片、视频和链接的URL
     */
    public static List<String> getUrls(@Nullable String html) {
        List<String> urls = new ArrayList<>();
        if (StringUtils.isBlank(html)) {
            return urls;
        }
        Document doc = Jsoup.parseBodyFragment(html);
        doc.select("img,source,a").forEach(element -> {
            switch (element.tagName()) {
                case "img":
                case "source": {
                    Optional.of(element.attr("src")).filter(url -> !url.isEmpty()).ifPresent(urls::add);
                    break;
                }
                case "a": {
                    Optional.of(element.attr("href")).filter(url -> !url.isEmpty()).ifPresent(urls::add);
                    break;
                }
                default:
            }
        });
        return urls;
    }

    /**
     * 下载html中的图片并且替换url
     *
     * @param html
     * @return
     */
    public static String downloadImageReplace(@Nullable String html) {
        if (StringUtils.isBlank(html)) {
            return html;
        }
        SiteDO siteDO = CmsContextUtil.getSite();
        final CommonResult<FileConfigRespVO> fileConfigResp = SpringUtil.getBean(FileConfigApi.class).getFileConfig(siteDO.getGlobalConfigDO().getUploadStoreConfigId().longValue());
        if (fileConfigResp.isSuccess()) {
            final FileConfigRespVO fileConfigRespData = fileConfigResp.getData();
            final String fileStoreDomain = fileConfigRespData.getConfig().getDomain();
            List<String> urls = getUrls(html);
            for (String url : urls) {
                if (url.startsWith("http")) {
                    String normalizeUrl = URLUtil.normalize(url);
                    //是否外网资源，是本站资源则跳过
                    if (normalizeUrl.startsWith(fileStoreDomain)) {
                        continue;
                    }
                    try{
                        // 创建请求头，添加Referer
                        HttpHeaders headers = new HttpHeaders();
                        headers.set("Referer", normalizeUrl); // 关键：设置Referer头
                        final byte[] bytes = HttpUtils.downloadBytes(normalizeUrl);
                        final String localFileUrl = SpringUtil.getBean(FileApi.class).createFile(bytes);
                        html = html.replace(url, localFileUrl);
                    }catch (Exception e){
                        log.error("下载资源失败{}",normalizeUrl);
                    }
                }
            }
        }
        return html;
    }

    /**
     * 下载html中的图片并且替换url
     *
     * @param html
     * @return
     */
    public static String crawlerDownloadImageReplace(@Nullable String html, String resUrlPrefix) {
        if (StringUtils.isBlank(html)) {
            return html;
        }
        List<String> urls = getUrls(html);
        for (String url : urls) {
            String downUrl = url;
            if (StringUtils.isNotBlank(resUrlPrefix)) {
                downUrl = resUrlPrefix + downUrl;
            }
            String normalizeUrl = URLUtil.normalize(downUrl);
            final byte[] bytes = HttpUtil.downloadBytes(normalizeUrl);
            final String localFileUrl = SpringUtil.getBean(FileApi.class).createFile(bytes);
            html = html.replace(url, localFileUrl);
        }
        return html;
    }
}
